package com.levi.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author shentong
 * @date 2022/1/9 6:17 PM
 * @description  Bean转换工具 List转List
 */
public class ConvertUtil {


    public static <T> List<T>  convertList(List<?> sources,Class<T> clazz){
        if (CollectionUtils.isEmpty(sources)) {
            return Collections.emptyList();
        }
        List<T> targets = new ArrayList<>(sources.size());
        convert(sources,targets,clazz);
        return targets;
    }

    public static <T> void convert(List<?> sources, List<T> targets, Class<T> clazz) {
        if (CollectionUtils.isEmpty(sources)) {
            return;
        }
        if (targets == null) {
            return;
        }
        targets.clear();
        for (Object source : sources) {
            try {
                T t = clazz.newInstance();
                BeanUtils.copyProperties(source,t);
                targets.add(t);
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
        }
    }
}
